package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewStub;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.weixin.paleituo.R;
import com.weixin.paleituo.annotation.InvoiceBeginType;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.InvoiceTipsBean;
import com.weixin.paleituo.bean.OrderInvoiceBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.RegisterProtocolPopupWindow;
import com.weixin.paleituo.view.ShopCarToastView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 发票设置界面
 * 发票类型一种：纸质发票(目前写死为纸质发票)
 * 三种发票抬头：个人、单位、不开发票 {@link com.weixin.paleituo.annotation.InvoiceBeginType}
 * 单位分为两种：普通发票、增值税发票
 *
 * @author fengzhen
 * @version v1.0, 2018/4/1
 */
public class OrderInvoiceActivity extends BasePersonActivity {

    @BindView(R.id.radiogroup_begin_activity_order_invoice)
    RadioGroup mRadiogroupBeginActivityOrderInvoice;
    @BindView(R.id.stub_group_activity_order_invoice)
    ViewStub mStubGroupActivityOrderInvoice;
    @BindView(R.id.stub_personal_activity_order_invoice)
    ViewStub mStubPersonalActivityOrderInvoice;

    private DynamicLoadingHolder mDynamicLoadingHolder = new DynamicLoadingHolder();

    private OrderInvoiceBean mGroupInfo;
    private String proContent;
    private Dialog mLoadingDialog;
    private RegisterProtocolPopupWindow mInvoiceTipsPop;

    private OrderInvoiceBean mInvoice;

    /**
     * 发票抬头类型
     */
    @InvoiceBeginType
    private int mBeginType = InvoiceBeginType.TYPE_PERSONAL;

    public static Intent call2OrderInvoiceActivity(Context context, OrderInvoiceBean invoice) {
        Intent intent = new Intent(context, OrderInvoiceActivity.class);
        intent.putExtra(Contans.INTENT_DATA, invoice);
        return intent;
    }

    @Override
    protected View getContentView(Context context) {
        return UIUtils.inflate(this, R.layout.activity_order_invoice);
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("发票");
        mTvSmalTitle.setText("发票须知");
        mTvSmalTitle.setTextColor(ContextCompat.getColor(this, R.color.c_ff999999));
        mTvSmalTitle.setVisibility(View.VISIBLE);

        mInvoice = getIntent().getParcelableExtra(Contans.INTENT_DATA);

        if (mInvoice != null) {
            switch (mInvoice.getTitle()) {
                case 1:
                    mBeginType = InvoiceBeginType.TYPE_PERSONAL;
                    break;
                case 2:
                    mBeginType = InvoiceBeginType.TYPE_GROUP;
                    break;
                case 3:
                    mBeginType = InvoiceBeginType.TYPE_NON;
                    break;
            }
        } else {
            mInvoice = new OrderInvoiceBean();
        }

        setDefaultCheckBegin();
    }

    @Override
    protected void save(final View v) {
        super.save(v);
        if (StringUtils.isEmpty(proContent)) {
            Observable observable = ApiUtils.getApi().getInvoiceTips(Contans.defaultToken, BaseApplication.getUserId())
                    .compose(RxHelper.getObservaleTransformer())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {

                            if (mLoadingDialog == null) {
                                mLoadingDialog = LoadingDialogUtils.createLoadingDialog(OrderInvoiceActivity.this, "");
                            }
                            mLoadingDialog.show();
                        }
                    }).subscribeOn(AndroidSchedulers.mainThread());
            HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<InvoiceTipsBean>(this) {

                @Override
                protected void _onNext(StatusCode<InvoiceTipsBean> registerProBeanStatusCode) {
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                    InvoiceTipsBean dataProBean = registerProBeanStatusCode.getData();

                    proContent = dataProBean.getDetail();
                    if (!StringUtils.isEmpty(proContent)) {
                        //弹出协议
                        if (mInvoiceTipsPop == null) {
                            mInvoiceTipsPop = new RegisterProtocolPopupWindow(OrderInvoiceActivity.this, proContent);
                        }
                        mInvoiceTipsPop.showAtLocation(v, Gravity.CENTER, 0, 0);
                    }
                }

                @Override
                protected void _onError(String message) {
                    ToastUtils.makeText(message);
                    LoadingDialogUtils.closeDialog(mLoadingDialog);

                }

            }, "", lifecycleSubject, false, true);

        } else {
            //弹出协议
            if (mInvoiceTipsPop == null) {
                mInvoiceTipsPop = new RegisterProtocolPopupWindow(this, proContent);
            }
            mInvoiceTipsPop.showAtLocation(v, Gravity.CENTER, 0, 0);
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }

    @Override
    protected void returnMainActivity(View v) {
        super.returnMainActivity(v);
        onBackPressed();
    }

    @OnClick({R.id.btn_commit_activity_order_invoice})
    public void onClickM(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.btn_commit_activity_order_invoice:
                switch (mBeginType) {
                    case InvoiceBeginType.TYPE_PERSONAL:
                        String personalName = mDynamicLoadingHolder.getPersonalName();
                        if (TextUtils.isEmpty(personalName)) {
                            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
                            shopCarToastView.setIcon(R.mipmap.address_error);
                            shopCarToastView.setText("请输入个人姓名");
                            shopCarToastView.setDuration(Toast.LENGTH_LONG);
                            shopCarToastView.show();
                            break;
                        }
                        if (!UIUtils.isNick(personalName)) {
                            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
                            shopCarToastView.setIcon(R.mipmap.address_error);
                            shopCarToastView.setText("个人姓名只能输入汉字、字母或数字");
                            shopCarToastView.setDuration(Toast.LENGTH_LONG);
                            shopCarToastView.show();
                            break;
                        }
                        mInvoice.setType(1);
                        mInvoice.setTitle(1);
                        mInvoice.setName(personalName);
                        mInvoice.setInvoiceName("纸质（个人）");
                        intent.putExtra(Contans.INTENT_DATA, mInvoice);
                        setResult(RESULT_OK, intent);
                        finish();
                        break;
                    case InvoiceBeginType.TYPE_GROUP:
                        switch (mDynamicLoadingHolder.getmGroupInvoiceType()) {
                            case InvoiceBeginType.TYPE_GROUP_NORMAL:
                                String groupName = mDynamicLoadingHolder.getGroupName();
                                String groupKey = mDynamicLoadingHolder.getGroupKey();
                                if (TextUtils.isEmpty(groupName)) {
                                    ShopCarToastView shopCarToastView = new ShopCarToastView(this);
                                    shopCarToastView.setIcon(R.mipmap.address_error);
                                    shopCarToastView.setText("请填写单位名称");
                                    shopCarToastView.setDuration(Toast.LENGTH_LONG);
                                    shopCarToastView.show();
                                    break;
                                }
                                if (!UIUtils.isNick(groupName)){
                                    ShopCarToastView shopCarToastView = new ShopCarToastView(this);
                                    shopCarToastView.setIcon(R.mipmap.address_error);
                                    shopCarToastView.setText("单位名称只能输入汉字、字母或数字");
                                    shopCarToastView.setDuration(Toast.LENGTH_LONG);
                                    shopCarToastView.show();
                                    break;
                                }
                                if (TextUtils.isEmpty(groupKey)) {
                                    ShopCarToastView shopCarToastView = new ShopCarToastView(this);
                                    shopCarToastView.setIcon(R.mipmap.address_error);
                                    shopCarToastView.setText("请填写纳税人识别号");
                                    shopCarToastView.setDuration(Toast.LENGTH_LONG);
                                    shopCarToastView.show();
                                    break;
                                }
                                mInvoice.setType(1);
                                mInvoice.setTitle(2);
                                mInvoice.setGenre(1);
                                mInvoice.setName(groupName);
                                mInvoice.setNumber(groupKey);
                                mInvoice.setInvoiceName("普通（" + groupName + "）");
                                intent.putExtra(Contans.INTENT_DATA, mInvoice);
                                setResult(RESULT_OK, intent);
                                finish();
                                break;
                            case InvoiceBeginType.TYPE_GROUP_TAX:
                                if (mDynamicLoadingHolder.checkTax()) {
                                    mInvoice.setType(1);
                                    mInvoice.setTitle(2);
                                    mInvoice.setGenre(2);
                                    mInvoice.setInvoiceName("专用发票(" + mInvoice.getName() + ")");
                                    intent.putExtra(Contans.INTENT_DATA, mInvoice);
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                                break;
                        }
                        break;
                    case InvoiceBeginType.TYPE_NON:
                        mInvoice.setType(1);
                        mInvoice.setTitle(3);
                        mInvoice.setInvoiceName("不开发票");
                        intent.putExtra(Contans.INTENT_DATA, mInvoice);
                        setResult(RESULT_OK, intent);
                        finish();
                        break;
                }
                break;
        }
    }

    @OnCheckedChanged({R.id.rbtn_personal_activity_order_invoice, R.id.rbtn_group_activity_order_invoice, R.id.rbtn_null_activity_order_invoice})
    public void onCheckChange(CompoundButton view, boolean checked) {
        if (checked) {
            switch (view.getId()) {
                case R.id.rbtn_personal_activity_order_invoice:
                    mBeginType = InvoiceBeginType.TYPE_PERSONAL;
                    mInvoice.setTitle(1);
                    mDynamicLoadingHolder.loadPersonalStub(mStubPersonalActivityOrderInvoice, mInvoice, true);
                    break;
                case R.id.rbtn_group_activity_order_invoice:
                    mBeginType = InvoiceBeginType.TYPE_GROUP;
                    mInvoice.setTitle(2);
                    mDynamicLoadingHolder.loadGroupStub(mStubGroupActivityOrderInvoice, mInvoice, true);
                    break;
                case R.id.rbtn_null_activity_order_invoice:
                    mBeginType = InvoiceBeginType.TYPE_NON;
                    mInvoice.setTitle(3);
                    mDynamicLoadingHolder.loadPersonalStub(mStubPersonalActivityOrderInvoice, mInvoice, false);
                    mDynamicLoadingHolder.loadGroupStub(mStubGroupActivityOrderInvoice, mInvoice, false);
                    break;
            }
        } else {
            switch (view.getId()) {
                case R.id.rbtn_personal_activity_order_invoice:
                    mDynamicLoadingHolder.loadPersonalStub(mStubPersonalActivityOrderInvoice, mInvoice, false);
                    break;
                case R.id.rbtn_group_activity_order_invoice:
                    mDynamicLoadingHolder.loadGroupStub(mStubGroupActivityOrderInvoice, mInvoice, false);
                    break;
                case R.id.rbtn_null_activity_order_invoice:
                    break;
            }
        }
    }

    /**
     * 设置默认选中发票抬头
     */
    private void setDefaultCheckBegin() {
        switch (mBeginType) {
            case InvoiceBeginType.TYPE_PERSONAL:
                mRadiogroupBeginActivityOrderInvoice.check(R.id.rbtn_personal_activity_order_invoice);
                break;
            case InvoiceBeginType.TYPE_GROUP:
                mRadiogroupBeginActivityOrderInvoice.check(R.id.rbtn_group_activity_order_invoice);
                break;
            case InvoiceBeginType.TYPE_NON:
                mRadiogroupBeginActivityOrderInvoice.check(R.id.rbtn_null_activity_order_invoice);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        mDynamicLoadingHolder.unbindButterKnife();
        super.onDestroy();
    }

    /**
     * 动态加载不同布局
     *
     * @author fengzhen
     * @version v1.0, 2018/4/2
     */
    class DynamicLoadingHolder {

        @BindView(R.id.radiogroup_type_layout_group_activity_order_invoice)
        RadioGroup mRadioGroupType;
        @BindView(R.id.rbtn_normal_layout_group_activity_order_invoice)
        RadioButton mRbtnNormal;
        @BindView(R.id.rbtn_group_layout_group_activity_order_invoice)
        RadioButton mRbtnGroup;
        @BindView(R.id.linear_normal_detail_layout_group_activity_order_invoice)
        LinearLayout mLinearNormalDetail;
        @BindView(R.id.scroll_detail_layout_group_activity_order_invoice)
        LinearLayout mScrollGroupDetail;
        @BindView(R.id.edit_name_layout_group_activity_order_invoice)
        EditText mEditGroupName;
        @BindView(R.id.edit_key_layout_group_activity_order_invoice)
        EditText mEditGroupkey;
        @BindView(R.id.tv_name_table_group)
        EditText mTvNameTableGroup;
        @BindView(R.id.tv_num_table_group)
        EditText mTvNumTableGroup;
        @BindView(R.id.tv_address_table_group)
        EditText mTvAddressTableGroup;
        @BindView(R.id.tv_phone_table_group)
        EditText mTvPhoneTableGroup;
        @BindView(R.id.tv_bank_table_group)
        EditText mTvBankTableGroup;
        @BindView(R.id.tv_bank_id_table_group)
        EditText mTvBankIdTableGroup;

        private EditText mEditPersonalName;

        // 默认选中普通发票
        @InvoiceBeginType
        private int mGroupInvoiceType = InvoiceBeginType.TYPE_GROUP_NORMAL;

        /**
         * 保存Unbinder，用于释放资源
         */
        private List<Unbinder> mUnbinderList = new ArrayList<>();

        /**
         * 获取ButterKnife进行资源释放
         */
        public void unbindButterKnife() {
            for (Unbinder unbinder :
                    mUnbinderList) {
                unbinder.unbind();
            }
        }

        @InvoiceBeginType
        public int getmGroupInvoiceType() {
            return mGroupInvoiceType;
        }

        public void setmGroupInvoiceType(@InvoiceBeginType int mGroupInvoiceType) {
            this.mGroupInvoiceType = mGroupInvoiceType;
        }

        /**
         * 获取个人抬头用户名
         */
        public String getPersonalName() {
            if (mEditPersonalName != null) {
                return mEditPersonalName.getText().toString();
            }
            return null;
        }

        /**
         * 获取单位普通 单位名称
         */
        public String getGroupName() {
            if (mEditGroupName != null) {
                return mEditGroupName.getText().toString();
            }
            return null;
        }

        /**
         * 获取单位普通 纳税人识别码
         */
        public String getGroupKey() {
            if (mEditGroupkey != null) {
                return mEditGroupkey.getText().toString().toUpperCase();
            }
            return null;
        }

        /**
         * 检查增值税数据正确性
         */
        public boolean checkTax() {
            String name = mTvNameTableGroup.getText().toString();
            String number = mTvNumTableGroup.getText().toString().toUpperCase();
            String address = mTvAddressTableGroup.getText().toString();
            String phone = mTvPhoneTableGroup.getText().toString();
            String bank = mTvBankTableGroup.getText().toString();
            String bankId = mTvBankIdTableGroup.getText().toString();
            if (TextUtils.isEmpty(name)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"请填写单位名称");
                return false;
            }
            if (!UIUtils.isNick(name)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"单位名称只能输入汉字、字母或数字");
                return false;
            }
            if (TextUtils.isEmpty(number)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"请填写纳税人识别号");
                return false;
            }
            if (TextUtils.isEmpty(address)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"请填写注册地址");
                return false;
            }
            if (!UIUtils.isNick(address)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"注册地址只能输入汉字、字母或数字");
                return false;
            }
            if (TextUtils.isEmpty(phone)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"请填写注册电话");
                return false;
            }
            if (TextUtils.isEmpty(bank)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"请填写开户银行");
                return false;
            }
            if (!UIUtils.isNick(bank)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"开户银行只能输入汉字、字母或数字");
                return false;
            }
            if (TextUtils.isEmpty(bankId)) {
                UIUtils.showCarToast(OrderInvoiceActivity.this,1,"请填写银行账户");
                return false;
            }
            mInvoice.setName(name);
            mInvoice.setNumber(number);
            mInvoice.setAddress(address);
            mInvoice.setPhone(phone);
            mInvoice.setBlank(bank);
            mInvoice.setAccount(bankId);
            return true;
        }

        @OnCheckedChanged({R.id.rbtn_normal_layout_group_activity_order_invoice,
                R.id.rbtn_group_layout_group_activity_order_invoice})
        public void onGroupCheckChange(CompoundButton view, boolean checked) {
            if (checked) {
                switch (view.getId()) {
                    case R.id.rbtn_normal_layout_group_activity_order_invoice:
                        mGroupInvoiceType = InvoiceBeginType.TYPE_GROUP_NORMAL;
                        mScrollGroupDetail.setVisibility(View.GONE);
                        mLinearNormalDetail.setVisibility(View.VISIBLE);

                        break;
                    case R.id.rbtn_group_layout_group_activity_order_invoice:
                        mGroupInvoiceType = InvoiceBeginType.TYPE_GROUP_TAX;
                        mScrollGroupDetail.setVisibility(View.VISIBLE);
                        mLinearNormalDetail.setVisibility(View.GONE);
                        break;
                }
            }
        }

        /***
         * 加载个人抬头类型
         */
        public void loadPersonalStub(@NonNull ViewStub stub, OrderInvoiceBean invoice, boolean visible) {
            View inflate = null;
            try {
                if (visible) {
                    inflate = stub.inflate();
                    stub.setTag(inflate);
                    mEditPersonalName = inflate.findViewById(R.id.edit_layout_personal_activity_order_invoice);
                }
            } catch (Exception e) {
                inflate = (View) stub.getTag();
            } finally {
                stub.setVisibility(visible ? View.VISIBLE : View.GONE);
                if (visible) {
                    mEditPersonalName.setText(invoice.getName());
                }
            }
        }

        /***
         * 加载单位抬头类型
         */
        public void loadGroupStub(@NonNull ViewStub stub, OrderInvoiceBean invoice, boolean visible) {
            View inflate = null;
            try {
                if (visible) {
                    inflate = stub.inflate();
                    stub.setTag(inflate);
                    mUnbinderList.add(ButterKnife.bind(this, inflate));
                    if (invoice.getGenre() == 1) {
                        // 普通发票
                        mRbtnNormal.setChecked(true);
                        mEditGroupName.setText(invoice.getName());
                        mEditGroupkey.setText(invoice.getNumber());
                    } else if (invoice.getGenre() == 2) {
                        // 增值税发票
                        mRbtnGroup.setChecked(true);
                        mTvNameTableGroup.setText(invoice.getName());
                        mTvNumTableGroup.setText(invoice.getNumber());
                        mTvAddressTableGroup.setText(invoice.getAddress());
                        mTvPhoneTableGroup.setText(invoice.getPhone());
                        mTvBankTableGroup.setText(invoice.getBlank());
                        mTvBankIdTableGroup.setText(invoice.getAccount());
                    } else {
                        mRbtnNormal.setChecked(true);
                    }

                    // 初始化增值税数据
                    if (invoice.getGenre() != 2 && mGroupInfo == null) {
                        Observable observable = ApiUtils.getApi().getInvoiceGroupInfo(BaseApplication.getToken(), BaseApplication.getUserId())
                                .compose(RxHelper.getObservaleTransformer())
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(Disposable disposable) throws Exception {
                                        if (mLoadingDialog == null) {
                                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(OrderInvoiceActivity.this, "");
                                        }
                                        mLoadingDialog.show();
                                    }
                                }).subscribeOn(AndroidSchedulers.mainThread());
                        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderInvoiceBean>(OrderInvoiceActivity.this) {
                            @Override
                            protected void _onNext(StatusCode<OrderInvoiceBean> registerProBeanStatusCode) {
                                LoadingDialogUtils.closeDialog(mLoadingDialog);
                                mGroupInfo = registerProBeanStatusCode.getData();
                                if (mGroupInfo != null) {
                                    mTvNameTableGroup.setText(mGroupInfo.getName());
                                    mTvNumTableGroup.setText(mGroupInfo.getNumber());
                                    mTvAddressTableGroup.setText(mGroupInfo.getAddress());
                                    mTvPhoneTableGroup.setText(mGroupInfo.getPhone());
                                    mTvBankTableGroup.setText(mGroupInfo.getBlank());
                                    mTvBankIdTableGroup.setText(mGroupInfo.getAccount());
                                }
                            }

                            @Override
                            protected void _onError(String message) {
                                ToastUtils.makeText(message);
                                LoadingDialogUtils.closeDialog(mLoadingDialog);
                            }

                        }, "", lifecycleSubject, false, true);
                    }
                }
            } catch (Exception e) {
                inflate = (View) stub.getTag();
            } finally {
                stub.setVisibility(visible ? View.VISIBLE : View.GONE);
            }
        }
    }
}
